﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Xml.Linq;
using SharePhone.Common;
using SharePhone.Common.List;
using SharePhone.Provider;

namespace SharePhone.Core
{
    public class BaseItemList<T> : ObservableCollection<T> where T : BaseItem, new()
    {
        public BaseItemList()
        {
            LastRefreshTimeStamp = DateTime.Now;
        }

        public DateTime LastRefreshTimeStamp { get; internal set; }

        public SPList<T> ParentList { get; set; }

        /// <summary>
        /// Number of items to return from list (if 0, returns the default rowlimit from the view)
        /// </summary>
        public int RowLimit { get; set; }

        public void LoadAllItems()
        {
            if (ParentList == null)
                throw new ArgumentNullException("ParentList", "ParentList cannot be NULL");
            if (ParentList.ParentWeb == null)
                throw new ArgumentNullException("ParentList.ParentWeb","ParentList does not have a ParentWeb");
            ListItemProvider.GetListItems(ParentList.ParentWeb, ParentList, RowLimit, ItemsUpdated, null,
                                          ParentList.ParentWeb.Settings.Credentials);
        }

        public new void Add(T item)
        {
            item.ParentList = ParentList;
            if (item.State == ItemState.New)
                item.Update();
            base.Add(item);
        }

        public T Add()
        {
            var newItem = new T();
            Add(newItem);
            return newItem;
        }

        /// <summary>
        /// Refreshes all items in this list by doing a fresh call to SharePoint.
        /// </summary>
        public void Refresh()
        {
            Clear();
            ListItemProvider.GetListItems(ParentList.ParentWeb, ParentList, RowLimit, ItemsUpdated, null,
                                          ParentList.ParentWeb.Settings.Credentials);
        }

        public void Update(ListItemsUpdateCompleted callback)
        {
            var batch = new XElement("Batch");
            batch.SetAttributeValue("OnError", "Continue");
            batch.SetAttributeValue("ListVersion", "1");
            batch.SetAttributeValue("ViewName", string.Empty);
            int id = 1;
            IEnumerable<T> updateItems = from item in this
                                         where item.UpdateType != BaseCoreObject.UpdateMode.None
                                         select item;
            if (updateItems.Count() == 0)
                return;
            foreach (T item in updateItems)
            {
                XElement method = item.GenerateWebServiceUpdateFragment(id++);
                if (method != null)
                    batch.Add(method);
            }
            ListItemProvider.UpdateListItems(ParentList, batch, callback);
        }

        private void ItemsUpdated(BaseItemList<T> items)
        {
            foreach (T item in items)
            {
                T existingItem = this.Where(i => i.SPListItemId == item.SPListItemId).FirstOrDefault();
                if (existingItem == null)
                    Add(item);
                else
                {
                    Remove(existingItem);
                    Add(item);
                }
            }
            LastRefreshTimeStamp = DateTime.Now;
            FireItemsLoaded();
        }

        #region Cachestuff

        internal CacheStatus CacheStatus
        {
            get
            {
                ContextSettings settings = ParentList.ParentWeb.Settings;
                var minutesSinceLastRefresh = (int) (DateTime.Now - LastRefreshTimeStamp).TotalMinutes;
                if (minutesSinceLastRefresh > settings.CacheTimeout)
                    return CacheStatus.Old;
                return CacheStatus.Fresh;
            }
        }

        public void InvalidateCache()
        {
            LastRefreshTimeStamp = DateTime.MinValue;
        }

        #endregion

        #region Events

        public event ItemsLoadCompleteHandler ItemsLoaded;

        protected void FireItemsLoaded()
        {
            if (ItemsLoaded != null)
                ItemsLoaded(this, new EventArgs());
        }

        #endregion
    }
}